﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System;
using System.Collections.Generic;

namespace NeoPatterns.Patterns.Cache
{
    public static class CacheExtension
    {
        /// <summary>
        /// Returns a value from the cache.
        /// Throws exception if the key is not in cache
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TValue Get<TKey, TValue>(this ICache<TKey, TValue> cache, TKey key)
        {
            TValue value;
            if (!cache.TryGet(key, out value))
                throw new KeyNotFoundException(key.ToString());
            return value;
        }

        /// <summary>
        /// Gets a value from cache, or creates it and adds it to cache
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="getValue">Method creating value for given key</param>
        /// <returns></returns>
        public static TValue Get<TKey, TValue>(this ICache<TKey, TValue> cache, TKey key, Func<TKey, TValue> getValue)
        {
            TValue value;
            if (!cache.TryGet(key, out value))
            {
                value = getValue(key);
                cache.Set(key, value);
            }
            return value;
        }
    }
}